/*
 * @Author: hongbin
 * @Date: 2023-10-17 17:42:52
 * @LastEditors: hongbin
 * @LastEditTime: 2023-11-20 10:26:13
 * @Description:模拟 GraphQL
 */
import { ObjectId } from "mongodb";
import { PersonnelModel } from "./Personnel.js";
import { ProjectModel } from "./Project.js";
import { RoleModel } from "./Role.js";
import { Manager } from "./index.js";

const findOneGraph = {
    collection: "roles",
    operation: {
        name: "findOne",
        params: [{ desc: "管理员" }],
    },
};

export class Graph {
    models = {
        roles: RoleModel,
        personnel: PersonnelModel,
        projects: ProjectModel,
    };
    modelsManager = Object.keys(this.models).reduce((p, c) => {
        p[c] = new Manager(this.models[c]);
        return p;
    }, {});

    constructor(app) {
        this.app = app;
        // console.log("modelsManager:", this.modelsManager);
        this.listen();
    }

    listen() {
        this.app.post("/graph", (req, res, next) => {
            if (req.method.toLowerCase() == "post") {
                console.log(req.payload);

                const payload = req.payload;
                if (!payload) return res.status(567).json("传参不正确");
                const manager = this.modelsManager[payload.collection];

                if (!manager)
                    return res
                        .status(568)
                        .json("没有集合名： " + payload.collection);
                if (!manager[payload.operation.name])
                    return res
                        .status(569)
                        .json(
                            "该集合没有提供方法名： " + payload.operation.name
                        );
                this.findIdTransform(payload);
                // console.log("方法：", manager[payload.operation.name]);
                manager[payload.operation.name](...payload.operation.params)
                    .then(data => {
                        console.log("data", data);
                        res.json(data);
                    })
                    .catch(err => {
                        console.log(err);
                        res.status(570).json({
                            err,
                            params: payload.operation.params,
                        });
                    });
            } else next();
        });
    }

    /** 找到传入的id 将其转换成ObjectId */
    findIdTransform(payload) {
        for (const args of payload.operation.params) {
            for (const key of Object.keys(args)) {
                if (
                    typeof args[key] == "string" &&
                    args[key].length === 24 &&
                    args[key].match(/^[a-z | \d]+$/)
                ) {
                    args[key] = new ObjectId(args[key]);
                }
            }
        }
    }
}
